package cn.hfatec.shms.hr.hrAssess.service;

import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.base.BaseDao;
import cn.hfatec.shms.advice.annotation.MysqlDataSource;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.constants.ShmsProperties;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.exception.NotAuthException;
import cn.hfatec.shms.hr.HrCheck;
import cn.hfatec.shms.hr.hrAssess.dao.HrAssessDao;
import cn.hfatec.shms.hr.hrAssess.model.HrAssess;
import cn.hfatec.shms.hr.hrAssess.model.HrAssessParams;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.utils.ExcelUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;


/**
 *
 * @author hfatec
 * @version 1.0
 *
 * the JAVA code is generate by middlegen
 *
 */
@Service("HrAssessService")
public class HrAssessService {

    public static final String BEAN_ID = "HrAssessService";

    //注入Dao层
    @Resource(name = "HrAssessDao")
    private HrAssessDao hrAssessDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;
    @Resource(name = "shmsProperties")
    private ShmsProperties shmsProperties;

    /**
     *
     * 查询数据
     *
     * @param hrAssessParams
     * @param page
     *
     */
    @Transactional
    public Table queryHrAssessTable(HrAssessParams hrAssessParams, Page page){

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", hrAssessParams);
        return baseDao.queryTableByPage("queryHrAssess", params, page);
    }

    /**
     *
     * 插入数据
     * @param hrAssess
     *
     */
    @Transactional
    public void saveHrAssess(HrAssess hrAssess) {
        if(hrAssess.getId() != null) {
            HrAssess result = getHrAssess(hrAssess.getId());
            if(result != null) {
                hrAssessDao.update(hrAssess);
            } else {
                hrAssessDao.insert(hrAssess);
            }
        } else {
            hrAssessDao.insert(hrAssess);
        }
    }

    /**
     *
     * 删除数据
     * @param id
     *
     */
    @Transactional
    public void deleteHrAssess(Integer id) {

        hrAssessDao.delete(id);
    }

    /**
     *
     * 删除数据
     * @param hrAssessList
     *
     */
    @Transactional
    public void deleteHrAssessBatch(List<String> hrAssessList) {
        for(String id : hrAssessList) {
            deleteHrAssess(Integer.valueOf(id));
        }
    }

    /**
     *
     * 根据ID获取数据
     * @param id
     *
     */
    @Transactional
    public HrAssess getHrAssess(Integer id) {

        return hrAssessDao.getHrAssessById(id);
    }



    /**
     * 导入数据
     *
     * @param path
     * @param request
     * @param response
     * @return
     * @throws java.io.IOException
     */
    @Transactional
    @MysqlDataSource
    public String importAssess(String path, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String filePath = path.substring(path.indexOf("/upload") + 7);
        User user = (User) request.getSession().getAttribute(ShmsConstant.LOGIN_USER_SESSION_NAME);
        if (user == null) {
            throw new NotAuthException("用户未授权");
        }
        String uploadPath = shmsProperties.getUploadPath();
        File file = new File(uploadPath + File.separator + filePath);
        boolean flag = false;
        String rule = "^1[358]\\d{9}$";
        String errorMsg = "";
        Workbook workbook = null;
        workbook = WorkbookFactory.create(file);
        Sheet sh = workbook.getSheetAt(0);//
        List<HrCheck> potentialCusts = this.buildCustWithAjaxUpload(sh);//
        if (potentialCusts != null && potentialCusts.size() > 0) {
            for (HrCheck hrCheck : potentialCusts) {
                //判读是否为有效数据
                if (hrCheck.isValid()) {
                    HrAssess hrAssess = (HrAssess) hrCheck.getObject();
                    saveHrAssess(hrAssess);
                    flag = true;
                } else {//无效数据
                    errorMsg += "第" + hrCheck.getRowNumber() + "行的姓名或录入日期为空，不能导入!";
                }
            }
        } else {
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "导入的文件无符合数据").toString();
        }

        if (flag) {
            if ("".equals(errorMsg)) {
                return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "导入成功!" + errorMsg).toString();
            }
            return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "部分导入成功!" + errorMsg).toString();
        } else {
            return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "导入失败!" + errorMsg).toString();
        }

    }



    /**
     * 读取潜在客户导入的数据
     *
     * @param sh
     * @return
     * @throws Exception
     */
    @Transactional
    @MysqlDataSource
    private List<HrCheck> buildCustWithAjaxUpload(Sheet sh) throws Exception {
        List<HrCheck> checks = new ArrayList<HrCheck>();
        int rows = sh.getLastRowNum() + 1 - sh.getFirstRowNum(); // 总行数
        List<CodeInfo> sexList = CodeInfoCache.getCodeInfo(CodeType.SEX);
//        List<CodeInfo> nationList = CodeInfoCache.getCodeInfo(CodeType.NATION);
        List<CodeInfo> tdTypeList = CodeInfoCache.getCodeInfo(CodeType.TD_TYPE);
//        List<CodeInfo> educationList = CodeInfoCache.getCodeInfo(CodeType.EDUCATION);

        ExcelUtil excelUtil = new ExcelUtil();

        for (int i = 1; i < rows; i++) {
            boolean flag = true;//数据是否有效(客户姓名，手机号存在)
            boolean flag2 = false;//判断是否该行有数据
            HrAssess hrAssess = new HrAssess();
            HrCheck hrCheck = new HrCheck();
            hrCheck.setRowNumber(i + 1);
            hrCheck.setValid(true);
            String str = "";//下拉框
            // HSSFRow row = sh.getRow(i);//excel97-2003写法
            Row row = sh.getRow(i);
//            int cols = row.getLastCellNum() + 1 - row.getFirstCellNum(); // 该行的总列数
            Iterator cells = row.cellIterator();

            while (cells.hasNext()) {
                //判断行数据的客户姓名和电话是否为空，某一项为空则不执行循环
                if (StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, 0)) || StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, 1))) {
                    for (int r = 0; r <= 10; r++) {
                        if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, r))) {
                            if (!flag2) {
                                hrCheck.setValid(false);
                                flag2 = true;
                            }
                        }
                    }
                    flag = false;
                    break;
                }
//                HSSFCell cell = (HSSFCell) cells.next();//excel97-2003写法
                XSSFCell cell = (XSSFCell) cells.next();
                String[] nameArry = {excelUtil.getStringRowCellValue(row, 0),
                        excelUtil.getStringRowCellValue(row, 1),
                        excelUtil.getStringRowCellValue(row, 2),
                        excelUtil.getStringRowCellValue(row, 3),
                        excelUtil.getStringRowCellValue(row, 4),
                        excelUtil.getStringRowCellValue(row, 5),
                        excelUtil.getStringRowCellValue(row, 6),
                        excelUtil.getStringRowCellValue(row, 7),
                        excelUtil.getStringRowCellValue(row, 8),
                        excelUtil.getStringRowCellValue(row, 9)
                };
                for (int j = 0; j < nameArry.length; j++) {
                    if (nameArry[j] != null) {
                        if (j == 0) { hrAssess.setEmployeeId(nameArry[j]);
                        } else if (j == 1) { hrAssess.setEmployeeName(nameArry[j]);
                        } else if (j == 2) {hrAssess.setYear(nameArry[j]);
                        } else if (j == 3) {hrAssess.setJxjd(nameArry[j]);
                        } else if (j == 4) {hrAssess.setPgjg(nameArry[j]);
                        } else if (j == 5) {hrAssess.setDevelopmentFirst(nameArry[j]);
                        } else if (j == 6) {hrAssess.setDevelopmentSecond(nameArry[j]);
                        } else if (j == 7) {hrAssess.setDevelopmentThird(nameArry[j]);
                        } else if (j == 8) {hrAssess.setDevelopmentFourh(nameArry[j]);
                        }else if (j == 9) {hrAssess.setDevelopmentFifth(nameArry[j]);
                        }
                    }
                }
            }
            if (flag) {
//                 list.add(cust);
                hrCheck.setObject(hrAssess);
                checks.add(hrCheck);
            } else {
//                TdCheck.setCustom(cust);
                if (flag2) {
                    checks.add(hrCheck);
                }
            }
        }
        return checks;
    }


}